package middleware

import (
	"github.com/gin-gonic/gin"
	"guns-go/global"
	"guns-go/model/request"
	"guns-go/model/response"
	"guns-go/service"
	"strconv"
)

// 拦截器
func CasbinHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		claims, _ := c.Get("claims")
		waitUse := claims.(*request.CustomClaims)

		//如果是超级管理员不进行权限校验
		if waitUse.AdminType == global.SuperAdmin {
			c.Next()
			return
		}
		// 获取请求的URI
		obj := c.Request.URL.RequestURI()

		//特殊路由处理
		if obj == "/getLoginUser" || obj == "/logout" {
			c.Next()
			return
		}

		// 获取请求方法
		act := c.Request.Method
		// 获取用户的角色
		roleIds := waitUse.UserRoleIds

		e := service.Casbin()

		success := false
		if roleIds != nil && len(roleIds) > 0 {
			for _, roleId := range roleIds {
				// 判断策略中是否存在
				success, _ = e.Enforce(strconv.Itoa(roleId), obj, act)
				if !success {
					break
				}
			}
		}

		// global.GVA_CONFIG.System.Env == "develop"
		if success {
			c.Next()
		} else {
			response.FailWithDetailed(gin.H{}, "权限不足", c)
			c.Abort()
			return
		}
	}
}
